package cn.ham.ms.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @author jianghan
 * @date 2018-10-24 16:29
 */
@Configuration
public class DataSourceConfig {

    private static Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;


    /**
     * 主库
     * @return
     */
    @Primary
    @Bean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        logger.info("master data source create.");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    /**
     * 从库
     * @return
     */
    @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        logger.info("slave data source create.");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
}
